package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.member.domain.Prop;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.domain.UserProp;
import cn.wolfcode.luowowo.member.mapper.PropMapper;
import cn.wolfcode.luowowo.member.mapper.UserPropMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.service.IUserPropService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserPropServiceImpl implements IUserPropService {

    @Autowired
    private UserPropMapper userPropMapper;

    @Autowired
    private PropMapper propMapper;

    @Autowired
    private IUserInfoService userInfoService;

    public List<UserProp> getUserPropByUserId(Long id) {
        return userPropMapper.selectUserPropByUserId(id);
    }

    public List<Prop> getMyProps(Long id) {
        List<Long> ids=userPropMapper.selectPropIdByUserId(id);
        List<Prop> list=new ArrayList<>();
        for (Long propId : ids) {
            Prop prop=propMapper.selectByPropId(propId);
            list.add(prop);
        }
        return list;
    }

    public void insert(Prop prop, Long uid) {
        List<Long> list = userPropMapper.selectPropIdByUserId(uid);
        for (Long id : list) {
            if(id==prop.getId()){
                throw new LogicException("你已经购买过了");
            }
        }
        UserInfo userInfo=userInfoService.get(uid);
        if(userInfo.getIntegral()<prop.getGold()){
            throw new LogicException("积分不够");
        }
        UserProp userProp=new UserProp();
        userProp.setDate(new Date());
        userProp.setProp_id(prop.getId());
        userProp.setUser(userInfo);
        userPropMapper.insert(userProp);
        userInfoService.updateIntegralByUserId(uid,prop.getGold());
        propMapper.updateTotalById(prop.getId());
    }
}
